const express = require('express')
const router = express.Router()
const { SuccessModel, ErrorModel } = require('../model/resModel')
const loginCheck = require('../middleware/loginCheck')
const {
  getList,
  getDetail,
  addBlog,
  updateBlog,
  delBlog
} = require('../controller/blog')

router.get('/list', (req, res, next) => {
  const author = req.query.author || ''
  const keyword = req.query.keyword || ''
  const result = getList(author, keyword)

  return result.then(data => {
    res.json(new SuccessModel(data))
  })
})

router.get('/detail', (req, res, next) => {
  const id = req.query.id
  const result = getDetail(id)

  return result.then(data => {
    res.json(new SuccessModel(data))
  })
})

router.post('/add', loginCheck, (req, res, next) => {
  req.body.author = req.session.username
  const result = addBlog(req.body)

  return result.then(data => {
    if (data) {
      res.json(new SuccessModel('新建博客成功'))
    } else {
      res.json(new ErrorModel('新建博客失败!'))
    }
  })
})

router.post('/update', loginCheck, (req, res, next) => {
  const id = req.query.id
  const result = updateBlog(id, req.body)

  return result.then(data => {
    if (data) {
      res.json(new SuccessModel('修改博客成功'))
    } else {
      res.json(new ErrorModel('修改博客失败!'))
    }
  })
})

router.post('/del', loginCheck, (req, res, next) => {
  const id = req.query.id
  const author = req.session.username
  const result = delBlog(id, author)

  return result.then(data => {
    if (data) {
      res.json(new SuccessModel('删除博客成功'))
    } else {
      res.json(new ErrorModel('删除博客失败!'))
    }
  })
})

module.exports = router
